package com.gitee.wsl.doc.prosemirror.transform.ext

import com.gitee.wsl.doc.prosemirror.model.fragment.Slice
import com.gitee.wsl.doc.prosemirror.model.fragment.ext.fitsTrivially
import com.gitee.wsl.doc.prosemirror.model.node.Node
import com.gitee.wsl.doc.prosemirror.model.node.ext.resolveSafe
import com.gitee.wsl.doc.prosemirror.transform.Fitter
import com.gitee.wsl.doc.prosemirror.transform.step.ReplaceStep
import com.gitee.wsl.doc.prosemirror.transform.step.Step

// ‘Fit’ a slice into a given position in the document, producing a [step](#transform.Step) that
// inserts it. Will return null if there's no meaningful way to insert the slice here, or inserting
// it would be a no-op (an empty slice over an empty range).
fun Node.replaceStep( from: Int, to: Int = from, slice: Slice = Slice.empty): Step? {
    val doc = this
    if (from == to && slice.size == 0) return null
    val (resolvedFrom, resolvedTo) = doc.resolveSafe(from, to) ?: return null
    // Optimization -- avoid work if it's obvious that it's not needed.
    if (slice.fitsTrivially(resolvedFrom, resolvedTo)) return ReplaceStep(from, to, slice)
    return Fitter(resolvedFrom, resolvedTo, slice).fit()
}

